package com.qf.mrmd.config;

import com.alibaba.fastjson.JSONObject;
import com.qf.mrmd.entity.SysUser;
import com.qf.mrmd.result.ResponseCode;
import com.qf.mrmd.service.SysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthorizedInterceptor implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(AuthorizedInterceptor.class);

    @Autowired
    private SysUserService sysUserService;

    public static final String[] noAuthentication = {
           "/sysUser/adminlogin",
            "/swagger-ui.html",
            "/webjars/springfox-swagger-ui/springfox.css",
            "/webjars/springfox-swagger-ui/swagger-ui.css",
            "/webjars/springfox-swagger-ui/swagger-ui-standalone-preset.js",
            "/webjars/springfox-swagger-ui/springfox.js",
            "/webjars/springfox-swagger-ui/swagger-ui-bundle.js",
            "/swagger-ui.html/swagger-resources/configuration/ui",
            "/swagger-ui.html/swagger-resources/configuration/security",
            "swagger-ui.html/swagger-resources",
            "/swagger-resources/configuration/security",
            "/swagger-resources/configuration/ui",
            "/swagger-resources"

    };

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        /**
         * 1.判断请求是否需要认证
         * 2.通过token去数据库中获取用户信息，成功则通过认证，否则返回登录页面
         * 拦截器：return true---通过  false----失败
         */
        String requestURI = request.getRequestURI();
        logger.info("本次请求的URI为："+requestURI);
        for (String uri : noAuthentication) {
            if (requestURI.equals(uri)){
                return true;
            }
        }
        //获取请求中的cookie（请求头中）
        String token = request.getHeader("token");
        //通过token去查找用户
        SysUser sysUser = sysUserService.queryUserBySysToken(token);
        //判断用户是否存在
        if (null == sysUser){
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("ecode", ResponseCode.AUTH_EXCEPTION.getEcode());
//            jsonObject.put("info",ResponseCode.AUTH_EXCEPTION.getInfo());
//            response.setContentType("text/html,charset=utf-8");
//            response.getWriter().write(jsonObject.toString());
//            response.getWriter().flush();
//            response.getWriter().close();
            return true;
        }
        return true;
    }
}
